package qimao.com.edu.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import qimao.com.edu.entity.Author;
import qimao.com.edu.service.AuthorService;
import qimao.com.edu.service.impl.AuthorServiceImpl;

@WebServlet("/admin/updateAuthor.do")
public class UpdateAuthorServlet extends HttpServlet {
    
    private AuthorService authorService = new AuthorServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        
    
        Integer authorId = Integer.parseInt(request.getParameter("authorId"));
        String authorName = request.getParameter("authorName");
        String authorNationality = request.getParameter("authorNationality");
        Integer authorWorksCount = Integer.parseInt(request.getParameter("authorWorksCount"));
        if (authorId == null) {
            result.put("message", "用户ID不能为空");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return;
        }
        
        Author author = new Author();
        author.setAuthorId(authorId);
        author.setPenName(authorName);
        author.setBirthPlace(authorNationality);
        author.setWorksCount(authorWorksCount);
        
        int rowsAffected = authorService.updateAuthor(author);
        
        if (rowsAffected > 0) {
            result.put("success", true);
            result.put("message", "用户信息更新成功");
        } else {
            result.put("message", "用户不存在或更新失败");
        }
        
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
